package com.cypher.encryptionanddecryption.fragment.protocol.kunlun;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.Spinner;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.cypher.encryptionanddecryption.R;
import com.cypher.encryptionanddecryption.activity.BluetoothCommunicationActivity;
import com.cypher.encryptionanddecryption.bean.CommunicationBean;
import com.cypher.encryptionanddecryption.bluetooth.BluetoothGattManager;
import com.cypher.encryptionanddecryption.fragment.protocol.AbstractProtocolFragment;
import com.cypher.encryptionanddecryption.util.HexUtils;
import com.cypher.encryptionanddecryption.util.KunLunProtocolUtils;

import org.apache.commons.lang3.StringUtils;

/**
 * 错误代码页面
 * @author: 古霸天
 * @date: 2020/11/23
 */
public class ErrCodeFragment extends AbstractProtocolFragment {
    // 远程关阀锁定
    private CheckBox RSV_lock;
    // 通讯模块故障
    private CheckBox commModuleFailure;
    // 上传过程中再次执行上传功能
    private CheckBox againUpload;
    // 计量模块错误
    private CheckBox meteringModuleErr;
    // 阀门泄露
    private CheckBox valveLeakage;
    // 预留量报警
    private CheckBox reserveAlarm;
    // 微小流量
    private CheckBox microFlow;
    // 温度传感器故障
    private CheckBox temperatureSensorFailure;
    // 磁干扰
    private CheckBox magneticDisturbance;
    // 过流
    private CheckBox overflowing;
    // 防拆
    private CheckBox tamper;
    // SIM卡故障
    private CheckBox SIMFailure;
    // 是否已透支
    private CheckBox whetherOverdrawn;
    // 信号弱或无信号
    private CheckBox weakOrNoSignal;
    /**
     * 多天未用气下拉框
     */
    private Spinner manyDaysNoGas;
    private final String[] manyDaysNoGasArray = {"正常", "一级多天", "二级多天"};
    /**
     * 操作对象
     */
    private CommunicationBean bean;
    private BluetoothCommunicationActivity activity;
    /**
     * 存放读错误代码二进制数据
     */
    private StringBuffer readErrBinary;
    public ErrCodeFragment(BluetoothCommunicationActivity activity, CommunicationBean bean) {
        this.activity = activity;
        this.bean = bean;
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_kunlun_err_code, container, false);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        manyDaysNoGas = view.findViewById(R.id.spinner_many_days_no_gas);
        ArrayAdapter adapter = new ArrayAdapter<String>(view.getContext(), R.layout.spinner_item, manyDaysNoGasArray);
        adapter.setDropDownViewResource(R.layout.dropdown_stytle);
        manyDaysNoGas.setAdapter(adapter);

        initCheckbox(view);
    }

    /**
     * 初始胡复选框控件
     * @param v
     */
    private void initCheckbox(View v) {
        RSV_lock = v.findViewById(R.id.checkbox_rsv_lock);
        commModuleFailure = v.findViewById(R.id.checkbox_comm_module_failure);
        againUpload = v.findViewById(R.id.checkbox_again_upload);
        meteringModuleErr = v.findViewById(R.id.checkbox_metering_module_err);
        valveLeakage = v.findViewById(R.id.checkbox_valve_leakage);
        reserveAlarm = v.findViewById(R.id.checkbox_reserve_alarm);
        microFlow = v.findViewById(R.id.checkbox_micro_flow);
        temperatureSensorFailure = v.findViewById(R.id.checkbox_temperature_sensor_failure);
        magneticDisturbance = v.findViewById(R.id.checkbox_magnetic_disturbance);
        overflowing = v.findViewById(R.id.checkbox_overflowing);
        tamper = v.findViewById(R.id.checkbox_tamper);
        SIMFailure = v.findViewById(R.id.checkbox_SIM_failure);
        whetherOverdrawn = v.findViewById(R.id.checkbox_whether_overdrawn);
        weakOrNoSignal = v.findViewById(R.id.checkbox_weak_or_no_signal);
    }

    @Override
    public void fillFragment(String data) {

        // 格式化数据
        String formatData = KunLunProtocolUtils.formatReceiveData(data);
        formatData = StringUtils.substring(formatData, 12, 24);

        readErrBinary = new StringBuffer();
        for (int i = 0; i < formatData.length() / 2; i++) {
            int intStr = Integer.parseInt(formatData.substring(2 * i, 2 * (i + 1)), 16);
            String binaryStr = HexUtils.paddingLeft(Integer.toBinaryString(intStr), 8);
            readErrBinary.append(HexUtils.hexReverse(binaryStr));
        }

        renderFragment(readErrBinary.toString());
        // 释放写数据按钮
        activity.setWriteBtnStatus(CommunicationBean.RWType.READ_WRITE);

    }
    @Override
    public String getHexCode(String rwType) {
        // 如果是只读的，hex码从实体中取
        if (StringUtils.equals("read", rwType))
            return KunLunProtocolUtils.getKunLunCommand(bean.getHexCode());
        // 如果是写数据，需要重新组包
        return  KunLunProtocolUtils.getKunLunSpecialCommand("00D6910006" + getErrHexData(readErrBinary.toString()));
    }

    @Override
    public boolean checkData(String data, int protocolId) {
        return super.checkData(data, protocolId);
    }


    private void renderFragment(String data) {

        clearFragment();

        if (StringUtils.equals("1", data.substring(5, 6))) RSV_lock.setChecked(true);
        else RSV_lock.setChecked(false);

        if (StringUtils.equals("1", data.substring(6, 7))) magneticDisturbance.setChecked(true);
        else magneticDisturbance.setChecked(false);

        if (StringUtils.equals("1", data.substring(7, 8))) overflowing.setChecked(true);
        else overflowing.setChecked(false);

        if (StringUtils.equals("1", data.substring(8, 9))) microFlow.setChecked(true);
        else microFlow.setChecked(false);

        if (StringUtils.equals("1", data.substring(9, 10))) microFlow.setChecked(true);
        else microFlow.setChecked(false);

        if (StringUtils.equals("00", data.substring(10, 12)))
            manyDaysNoGas.setSelection(0, true);
        else if (StringUtils.equals("01", data.substring(10, 12)))
            manyDaysNoGas.setSelection(1, true);
        else if (StringUtils.equals("10", data.substring(10, 12)))
            manyDaysNoGas.setSelection(2, true);

        if (StringUtils.equals("1", data.substring(16, 17))) commModuleFailure.setChecked(true);
        else commModuleFailure.setChecked(false);

        if (StringUtils.equals("1", data.substring(17, 18))) SIMFailure.setChecked(true);
        else SIMFailure.setChecked(false);

        if (StringUtils.equals("1", data.substring(18, 19))) weakOrNoSignal.setChecked(true);
        else weakOrNoSignal.setChecked(false);

        if (StringUtils.equals("1", data.substring(22, 23))) againUpload.setChecked(true);
        else againUpload.setChecked(false);

        if (StringUtils.equals("1", data.substring(24, 25))) meteringModuleErr.setChecked(true);
        else meteringModuleErr.setChecked(false);

        if (StringUtils.equals("1", data.substring(25, 26))) valveLeakage.setChecked(true);
        else valveLeakage.setChecked(false);

        if (StringUtils.equals("1", data.substring(26, 27))) tamper.setChecked(true);
        else tamper.setChecked(false);

        if (StringUtils.equals("1", data.substring(28, 29))) reserveAlarm.setChecked(true);
        else reserveAlarm.setChecked(false);

        if (StringUtils.equals("1", data.substring(30, 31))) temperatureSensorFailure.setChecked(true);
        else temperatureSensorFailure.setChecked(false);

        if (StringUtils.equals("1", data.substring(32, 33))) whetherOverdrawn.setChecked(true);
        else whetherOverdrawn.setChecked(false);

    }

    /**
     * 获取写错误代码
     * @param data 读错误代码数据
     * @return
     */
    public String getErrHexData(String data) {

        String bin0 = "0";
        String bin1 = "1";

        int position = 5;
        if (RSV_lock.isChecked()) data = setBinaryData(data, position, bin1);
        else data = setBinaryData(data, position, bin0);

        position = 6;
        if (magneticDisturbance.isChecked()) data = setBinaryData(data, position, bin1);
        else data = setBinaryData(data, position, bin0);

        position = 7;
        if (overflowing.isChecked()) data = setBinaryData(data, position, bin1);
        else data = setBinaryData(data, position, bin0);

        position = 8;
        if (microFlow.isChecked()) data = setBinaryData(data, position, bin1);
        else data = setBinaryData(data, position, bin0);

        if (manyDaysNoGas.getSelectedItemPosition() == 0)
            data = data.substring(0, 10) + "00" + data.substring(12);
        else if (manyDaysNoGas.getSelectedItemPosition() == 1)
            data = data.substring(0, 10) + "01" + data.substring(12);
        else if (manyDaysNoGas.getSelectedItemPosition() == 2)
            data = data.substring(0, 10) + "10" + data.substring(12);

        position = 16;
        if (commModuleFailure.isChecked()) data = setBinaryData(data, position, bin1);
        else data = setBinaryData(data, position, bin0);

        position = 17;
        if (SIMFailure.isChecked()) data = setBinaryData(data, position, bin1);
        else data = setBinaryData(data, position, bin0);

        if (StringUtils.equals("1", data.substring(18, 19))) weakOrNoSignal.setChecked(true);
        else weakOrNoSignal.setChecked(false);
        position = 17;
        if (SIMFailure.isChecked()) data = setBinaryData(data, position, bin1);
        else data = setBinaryData(data, position, bin0);

        if (StringUtils.equals("1", data.substring(22, 23))) againUpload.setChecked(true);
        else againUpload.setChecked(false);
        position = 17;
        if (SIMFailure.isChecked()) data = setBinaryData(data, position, bin1);
        else data = setBinaryData(data, position, bin0);

        position = 24;
        if (meteringModuleErr.isChecked()) data = setBinaryData(data, position, bin1);
        else data = setBinaryData(data, position, bin0);

        position = 25;
        if (valveLeakage.isChecked()) data = setBinaryData(data, position, bin1);
        else data = setBinaryData(data, position, bin0);

        position = 26;
        if (tamper.isChecked()) data = setBinaryData(data, position, bin1);
        else data = setBinaryData(data, position, bin0);

        position = 28;
        if (reserveAlarm.isChecked()) data = setBinaryData(data, position, bin1);
        else data = setBinaryData(data, position, bin0);

        position = 30;
        if (temperatureSensorFailure.isChecked()) data = setBinaryData(data, position, bin1);
        else data = setBinaryData(data, position, bin0);

        position = 32;
        if (whetherOverdrawn.isChecked()) data = setBinaryData(data, position, bin1);
        else data = setBinaryData(data, position, bin0);

        StringBuffer result = new StringBuffer();
        for (int i = 0; i < data.length() / 8; i++) {
            // 反转二进制
            String reverseStr = HexUtils.hexReverse(data.substring(i * 8, 8 * (i +1)));
            result.append(HexUtils.paddingLeft(Integer.toHexString(Integer.parseInt(reverseStr, 2)), 2));
        }

        return result.toString();
    }

    public String setBinaryData(String data, int position, String binStr) {
        return data.substring(0, position) + binStr + data.substring(position + 1);
    }

    /**
     * 恢复页面初始化
     */
    public void clearFragment() {
        RSV_lock.setChecked(false);
        commModuleFailure.setChecked(false);
        againUpload.setChecked(false);
        meteringModuleErr.setChecked(false);
        valveLeakage.setChecked(false);
        reserveAlarm.setChecked(false);
        microFlow.setChecked(false);
        temperatureSensorFailure.setChecked(false);
        magneticDisturbance.setChecked(false);
        overflowing.setChecked(false);
        tamper.setChecked(false);
        SIMFailure.setChecked(false);
        whetherOverdrawn.setChecked(false);
        weakOrNoSignal.setChecked(false);
        manyDaysNoGas.setSelection(0);
    }

    /**
     * 在写错误代码的时候需要读写流量系数
     * @param gattManager
     *      蓝牙通信管理类
     * @return
     */
    @Override
    public boolean specialCases(BluetoothGattManager gattManager, String rwType) {
        return super.specialCases(gattManager, rwType);
//        // 如果是读错误代码则不处理特殊情况
//        if (StringUtils.equals("read", rwType)) {
//            return true;
//        }
//        // -------------------------读流量系数-------------------------------------
//        // 获取读流量系数发送码
//        String readCode = KunLunProtocolUtils.getKunLunSpecialCommand("00B0911C01");
//        // 向列表添加数据
//        gattManager.addList("<- " + HexUtils.formatHex(readCode));
//        // 向蓝牙发送数据
//        gattManager.sendMsg(HexUtils.hexToBytes(readCode));
//        // 校验数据是否读取成功
//        if (!activity.checkData("读流量系数失败！")) {
//            return false;
//        }
//        // 校验成功设置校验结果为false
//        gattManager.setReceiveData(false);
//        String formatData = KunLunProtocolUtils.formatReceiveData(HexUtils.bytesToHex(gattManager.getBuf()));
//        String data = String.valueOf(Integer.parseInt(formatData.substring(6, 8), 16));
//
//        // -------------------------写流量系数-------------------------------------
//        // 获取写流量系数发送码
//        String writeCode = HexUtils.paddingLeft(
//                Integer.toHexString(Integer.parseInt(data)), 2);
//        writeCode = KunLunProtocolUtils.getKunLunCommand("12"+ writeCode);
//        // 向列表添加数据
//        gattManager.addList("<- " + HexUtils.formatHex(writeCode));
//        // 向蓝牙发送数据
//        gattManager.sendMsg(HexUtils.hexToBytes(writeCode));
//        if (!activity.checkData("写流量系数失败！")) {
//            return false;
//        }
//        // 校验成功设置校验结果为false
//        gattManager.setReceiveData(false);
//        if (!checkData(HexUtils.bytesToHex(gattManager.getBuf()),
//                bean.getProtocolId().ordinal())) {
//            Toast.makeText(activity, "写流量系数失败！", Toast.LENGTH_SHORT).show();
//
//        }
//        return true;
    }
}
